"use strict";
const electron = require("electron");
electron.ipcRenderer.on("update-message", (_, message) => {
  alert(message);
});
electron.ipcRenderer.on("update-ready", (_event, message) => {
  const notification = new Notification("应用更新", {
    body: message,
    icon: "../public/rb.ico"
  });
  setTimeout(() => notification.close(), 5e3);
});
if (Notification.permission !== "granted") {
  Notification.requestPermission().then((permission) => {
    if (permission === "granted") {
      console.log("用户已授权通知");
    } else {
      console.warn("用户未授权通知");
    }
  });
}
electron.contextBridge.exposeInMainWorld("ipcRenderer", {
  on(...args) {
    const [channel, listener] = args;
    return electron.ipcRenderer.on(channel, (event, ...args2) => listener(event, ...args2));
  },
  off(...args) {
    const [channel, ...omit] = args;
    return electron.ipcRenderer.off(channel, ...omit);
  },
  send(...args) {
    const [channel, ...omit] = args;
    return electron.ipcRenderer.send(channel, ...omit);
  },
  invoke(...args) {
    const [channel, ...omit] = args;
    return electron.ipcRenderer.invoke(channel, ...omit);
  }
});
electron.contextBridge.exposeInMainWorld("fileAPI", {
  navigateWithPlaywright: (url, orderNumbersArray, isHeadless) => electron.ipcRenderer.send("navigate-with-playwright", url, orderNumbersArray, isHeadless),
  downloadTemplate: async () => {
    try {
      return await electron.ipcRenderer.invoke("download-template");
    } catch (error) {
      console.error("Error fetching template:", error);
      return null;
    }
  },
  processExcelFile: (fileBuffer) => electron.ipcRenderer.invoke("process-excel-file", fileBuffer),
  readExcelData: (fileBuffer) => electron.ipcRenderer.invoke("read-excel-data", fileBuffer),
  openFile: (filePath) => electron.ipcRenderer.invoke("open-file", filePath),
  showItemInFolder: (filePath) => electron.ipcRenderer.invoke("show-item-in-folder", filePath),
  getFileFullPath: (file) => {
    if (!file || !(file instanceof File)) {
      throw new Error("无效的文件对象: 必须是File类型");
    }
    return electron.ipcRenderer.invoke("get-file-full-path", file);
  },
  // 获取桌面路径
  getDesktopPath: () => electron.ipcRenderer.invoke("get-desktop-path"),
  // 确保目录存在
  ensureDirectoryExists: (dirPath) => electron.ipcRenderer.invoke("ensure-directory-exists", dirPath),
  // 保存文件
  saveFile: (filePath, fileContent) => electron.ipcRenderer.invoke("save-file", filePath, fileContent),
  // 读取目录
  readDirectory: (dirPath) => electron.ipcRenderer.invoke("read-directory", dirPath),
  // 读取文件
  readFile: (filePath) => electron.ipcRenderer.invoke("read-file", filePath),
  // 写入文件
  writeFile: (filePath, content) => electron.ipcRenderer.invoke("write-file", filePath, content),
  // 删除文件
  deleteFile: (filePath) => electron.ipcRenderer.invoke("delete-file", filePath),
  // 显示文件选择对话框
  showOpenDialog: (options) => electron.ipcRenderer.invoke("show-open-dialog", options),
  // 检查文件是否存在
  checkFileExists: (filePath) => electron.ipcRenderer.invoke("check-file-exists", filePath)
});
electron.contextBridge.exposeInMainWorld("electron", {
  send: (channel, data) => {
    electron.ipcRenderer.send(channel, data);
  },
  // 从渲染进程发送消息到主进程的示例函数
  receive: (channel, func) => {
    electron.ipcRenderer.on(channel, (_event, ...args) => func(...args));
  }
  // 从主进程接收消息到渲染进程的示例函数注册器
});
electron.contextBridge.exposeInMainWorld("electronAPI", {
  send: (channel, data) => electron.ipcRenderer.send(channel, data),
  getPath: (name) => electron.ipcRenderer.invoke("get-app-path", name),
  getPluginPath: (pluginName) => {
    return electron.ipcRenderer.invoke("get-plugin-path", pluginName);
  },
  getPluginHtmlPath: (pluginName) => {
    return electron.ipcRenderer.invoke("get-plugin-html-path", pluginName);
  },
  getMainfestPath: (pluginName) => {
    return electron.ipcRenderer.invoke("get-mainfest-path", pluginName);
  },
  createPluginWindow: (pluginName, htmlPath) => electron.ipcRenderer.invoke("create-plugin-window", pluginName, htmlPath),
  closeWindow: () => electron.ipcRenderer.send("close-window"),
  isWindowOpen: (pluginName) => electron.ipcRenderer.invoke("is-window-open", pluginName),
  toggleMaximize: () => electron.ipcRenderer.invoke("toggle-maximize"),
  minimizeWindow: () => electron.ipcRenderer.invoke("minimize-window"),
  loadPlugin: (pluginId) => electron.ipcRenderer.invoke("load-plugin", pluginId),
  writeData: () => electron.ipcRenderer.invoke("write-data"),
  executeChildProcess: (command) => electron.ipcRenderer.invoke("execute-child-process", command),
  runPlugin: (pluginId) => electron.ipcRenderer.invoke("run-plugin", pluginId),
  downloadPlugin: (pluginId, downloadUrl) => electron.ipcRenderer.invoke("download-plugin", pluginId, downloadUrl),
  getSheetIds: () => electron.ipcRenderer.invoke("getSheetIds"),
  saveSheetIds: (ids) => electron.ipcRenderer.invoke("saveSheetIds", ids),
  readCellData: (spreadsheetId, range) => electron.ipcRenderer.invoke("read-cell-data", spreadsheetId, range),
  readColumnData: (spreadsheetId, range) => electron.ipcRenderer.invoke("google-api:readColumnData", spreadsheetId, range),
  readRowData: (spreadsheetId, range) => electron.ipcRenderer.invoke("google-api:readRowData", spreadsheetId, range),
  updateRowData: (spreadsheetId, plmCode, rowData, range) => electron.ipcRenderer.invoke("google-api:updateRowData", spreadsheetId, plmCode, rowData, range),
  getSheetNames: (spreadsheetId) => electron.ipcRenderer.invoke("getSheetNames", spreadsheetId),
  updatePartialColumns: (spreadsheetId, sheetName, plmCode, updates, range) => electron.ipcRenderer.invoke("update-partial-columns", spreadsheetId, sheetName, plmCode, updates, range),
  saveSettings: (settings) => electron.ipcRenderer.invoke("save-settings", settings),
  getUserSettings: () => electron.ipcRenderer.invoke("get-user-settings"),
  sendMonitoringData: (data) => electron.ipcRenderer.invoke("send-monitoring-data", data),
  getBatchCombineOrders: () => electron.ipcRenderer.invoke("get-batch-combine-orders"),
  // 控制台监控相关API (为了兼容性也在这里添加)
  getConsoleLogs: (limit) => electron.ipcRenderer.invoke("get-console-logs", limit),
  clearConsoleLogs: () => electron.ipcRenderer.invoke("clear-console-logs"),
  startConsoleMonitoring: () => electron.ipcRenderer.invoke("start-console-monitoring"),
  stopConsoleMonitoring: () => electron.ipcRenderer.invoke("stop-console-monitoring"),
  addConsoleLog: (level, message) => electron.ipcRenderer.invoke("add-console-log", level, message),
  onConsoleLog: (callback) => {
    electron.ipcRenderer.on("console-log", (_, log) => callback(log));
  },
  onConsoleLogsBatch: (callback) => {
    electron.ipcRenderer.on("console-logs-batch", (_, logs) => callback(logs));
  },
  onConsoleCleared: (callback) => {
    electron.ipcRenderer.on("console-cleared", () => callback());
  },
  removeConsoleLogListeners: () => {
    electron.ipcRenderer.removeAllListeners("console-log");
    electron.ipcRenderer.removeAllListeners("console-logs-batch");
    electron.ipcRenderer.removeAllListeners("console-cleared");
  }
});
electron.contextBridge.exposeInMainWorld("notification", {
  create(title, options) {
    return new Notification(title, options);
  },
  requestPermission() {
    return Notification.requestPermission();
  }
});
electron.contextBridge.exposeInMainWorld("playwrightAPI", {
  openBrowser: (url, headless) => electron.ipcRenderer.send("open-browser", url, headless),
  loginGPO: (url, headless) => electron.ipcRenderer.invoke("login-GPO", url, headless),
  orderListEntry: (url, headless) => electron.ipcRenderer.send("orderList-entry", url, headless),
  reportListEntry: (url, headless) => electron.ipcRenderer.send("reportList-entry", url, headless),
  // runBatchCombine: (address: string, headless: boolean, orders: string[]) => {
  //   return ipcRenderer.invoke('run-batch-combine', address, headless, orders);
  // },
  runNewSubcontract: (address, headless, allCellData) => {
    return electron.ipcRenderer.invoke("run-new-subcontract", address, headless, allCellData);
  }
});
electron.contextBridge.exposeInMainWorld("docxAPI", {
  processWordFile: (pluginName, reportData) => electron.ipcRenderer.invoke("process-word-file", pluginName, reportData),
  saveWordFile: (buffer, filename) => electron.ipcRenderer.invoke("save-word-file", buffer, filename),
  getWordTemplate: (pluginName) => electron.ipcRenderer.invoke("get-word-template", pluginName)
});
electron.contextBridge.exposeInMainWorld("htmlUIAPI", {
  injectWindowControls: () => {
    const controlsHTML = `
      <div class="buttons drag-region" id="window-controls" style="position: fixed; top: 0; right: 0; z-index: 9999;">
        <button class="minimize" onclick="window.electronAPI.minimizeWindow()">
          <svg viewBox="0 0 10.2 1" width="10" height="10"><rect height="1" width="10.2" y="50%" x="0"></rect></svg>
        </button>
        <button class="maximize" onclick="window.electronAPI.toggleMaximize()">
          <svg viewBox="0 0 10 10" width="10" height="10"><path d="M0,0v10h10V0H0z M9,9H1V1h8V9z"></path></svg>
        </button>
        <button class="close" onclick="window.electronAPI.closeWindow()">
          <svg viewBox="0 0 10 10" width="10" height="10"><polygon points="10.2,0.7 9.5,0 5.1,4.4 0.7,0 0,0.7 4.4,5.1 0,9.5 0.7,10.2 5.1,5.8 9.5,10.2 10.2,9.5 5.8,5.1"></polygon></svg>
        </button>
      </div>
      <style scoped>
        .drag-region {
          display: flex;
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 30px;
          -webkit-app-region: drag;
          background: transparent;
          justify-content: flex-end;
          align-items: center;
          padding-right: 10px;
        }

        button {
          width: 40px;
          margin-left: -5px;
          border: 0;
          outline: 0;
          background: transparent;
          transition: 0.2s;
          -webkit-app-region: no-drag;
        }

        button svg path, 
        button svg rect, 
        button svg polygon {
          fill: #ffffff;
        }

        button svg {
          width: 10px;
          height: 10px;
        }

        .close:hover {
          svg polygon {
            fill: #ff0000;
          }
        }

        .maximize:hover {
          svg path {
            fill: #53535f;
          }
        }

        .minimize:hover {
          svg rect {
            fill: #53535f;
          }
        }
      </style>
    `;
    document.body.insertAdjacentHTML("afterbegin", controlsHTML);
  }
});
electron.contextBridge.exposeInMainWorld("logAPI", {
  sendLog: (message = "[empty message]", type = "info", details) => {
    const validatedMessage = (message == null ? void 0 : message.toString()) || "invalid message";
    const validatedType = ["info", "warn", "error", "debug", "verbose", "silly"].includes(type) ? type : "info";
    electron.ipcRenderer.send("log-message", {
      message: validatedMessage,
      type: validatedType,
      details: (details == null ? void 0 : details.toString()) || ""
    });
  },
  onLogMessage: (callback) => {
    electron.ipcRenderer.on("log-message", (event, log) => {
      callback({
        message: ((log == null ? void 0 : log.message) || "").toString(),
        type: ["info", "warn", "error", "debug", "verbose", "silly"].includes(log == null ? void 0 : log.type) ? log.type : "info",
        details: ((log == null ? void 0 : log.details) || "").toString()
      });
    });
  }
});
let currentPluginTaskId = null;
electron.ipcRenderer.on("plugin-script-started", (_event, { taskId }) => {
  console.log(`插件脚本已启动，任务ID: ${taskId}`);
  currentPluginTaskId = taskId;
});
electron.contextBridge.exposeInMainWorld("pluginAPI", {
  checkPluginUpdate: (pluginId) => electron.ipcRenderer.invoke("check-plugin-update", pluginId),
  deletePlugin: (pluginId) => electron.ipcRenderer.invoke("delete-plugin", pluginId),
  runPluginScript: (params) => electron.ipcRenderer.invoke("run-plugin-script", params),
  stopPluginScript: () => {
    if (currentPluginTaskId) {
      console.log(`停止插件脚本，任务ID: ${currentPluginTaskId}`);
      const result = electron.ipcRenderer.invoke("stop-plugin-script", { taskId: currentPluginTaskId });
      currentPluginTaskId = null;
      return result;
    } else {
      console.warn("没有正在运行的插件脚本任务");
      return Promise.resolve({ success: false, error: "没有正在运行的插件脚本任务" });
    }
  },
  getCurrentTaskId: () => currentPluginTaskId,
  // 添加获取所有正在运行的插件任务的方法
  getRunningPluginTasks: () => electron.ipcRenderer.invoke("get-running-plugin-tasks")
});
electron.contextBridge.exposeInMainWorld("pyAPI", {
  runpyfile: (data) => electron.ipcRenderer.invoke("run-pyfile", data),
  runpyexe: (data) => electron.ipcRenderer.invoke("run-pyexe", data),
  // Python环境检查
  checkPythonEnvironment: () => electron.ipcRenderer.invoke("check-python-environment"),
  // 检查Python环境（为插件提供）
  checkPythonEnvironmentForPlugin: (pluginName) => electron.ipcRenderer.invoke("plugin-check-python-environment", pluginName),
  // 检查并下载Python环境（整合功能）
  checkAndDownloadPythonEnvironment: (pluginName) => electron.ipcRenderer.invoke("check-and-download-python-environment", pluginName),
  onPythonLogOutput: (callback) => {
    electron.ipcRenderer.on("python-log-output", (_event, logData) => callback(logData));
  },
  // 监听Python进程结束事件
  onPythonProcessEnded: (callback) => {
    electron.ipcRenderer.on("python-process-ended", (_event, endData) => callback(endData));
  },
  // 监听Python进程错误事件
  onPythonProcessError: (callback) => {
    electron.ipcRenderer.on("python-process-error", (_event, errorData) => callback(errorData));
  },
  // 监听Python环境状态事件
  onPythonEnvironmentStatus: (callback) => {
    electron.ipcRenderer.on("python-environment-status", (_event, statusData) => callback(statusData));
  },
  // 移除Python相关的事件监听器
  removePythonLogListeners: () => {
    electron.ipcRenderer.removeAllListeners("python-log-output");
    electron.ipcRenderer.removeAllListeners("python-process-ended");
    electron.ipcRenderer.removeAllListeners("python-process-error");
    electron.ipcRenderer.removeAllListeners("python-environment-status");
  }
});
electron.contextBridge.exposeInMainWorld("consoleAPI", {
  // 获取控制台日志
  getConsoleLogs: (limit) => electron.ipcRenderer.invoke("get-console-logs", limit),
  // 清空控制台日志
  clearConsoleLogs: () => electron.ipcRenderer.invoke("clear-console-logs"),
  // 开始控制台监控
  startConsoleMonitoring: () => electron.ipcRenderer.invoke("start-console-monitoring"),
  // 停止控制台监控
  stopConsoleMonitoring: () => electron.ipcRenderer.invoke("stop-console-monitoring"),
  // 手动添加日志条目
  addConsoleLog: (level, message) => electron.ipcRenderer.invoke("add-console-log", level, message),
  // 监听实时日志
  onConsoleLog: (callback) => {
    electron.ipcRenderer.on("console-log", (_, log) => callback(log));
  },
  // 监听批量日志
  onConsoleLogsBatch: (callback) => {
    electron.ipcRenderer.on("console-logs-batch", (_, logs) => callback(logs));
  },
  // 监听日志清空事件
  onConsoleCleared: (callback) => {
    electron.ipcRenderer.on("console-cleared", () => callback());
  },
  // 移除所有控制台相关的事件监听器
  removeConsoleLogListeners: () => {
    electron.ipcRenderer.removeAllListeners("console-log");
    electron.ipcRenderer.removeAllListeners("console-logs-batch");
    electron.ipcRenderer.removeAllListeners("console-cleared");
  }
});
electron.contextBridge.exposeInMainWorld("nodeAPI", {
  // 检查Node.js环境状态
  checkNodeEnvironment: () => electron.ipcRenderer.invoke("check-node-environment"),
  // 安装便携版Node.js
  installPortableNode: () => electron.ipcRenderer.invoke("install-portable-node"),
  // 检查插件依赖
  checkPluginDependencies: (pluginPath) => electron.ipcRenderer.invoke("check-plugin-dependencies", pluginPath),
  // 获取Node.js可执行文件路径
  getNodeExecutablePath: () => electron.ipcRenderer.invoke("get-node-executable-path"),
  // 监听Node.js安装进度
  onNodeInstallProgress: (callback) => {
    electron.ipcRenderer.on("node-install-progress", (_, progress) => callback(progress));
  },
  // 监听插件依赖安装进度
  onPluginDependencyProgress: (callback) => {
    electron.ipcRenderer.on("plugin-dependency-progress", (_, data) => callback(data));
  },
  // 移除Node.js相关的事件监听器
  removeNodeListeners: () => {
    electron.ipcRenderer.removeAllListeners("node-install-progress");
    electron.ipcRenderer.removeAllListeners("plugin-dependency-progress");
  }
});
